package com.example.network.demos.tcp.server.dongzong;

import com.example.network.demos.config.NetworkConfig;
import com.example.network.demos.tcp.domain.FileUploadFile;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.RandomAccessFile;
@Component
public class FileUploadServerHandlerDongzong extends ChannelInboundHandlerAdapter {
    private int byteRead;
    private volatile int start = 0;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof FileUploadFile) {
            FileUploadFile ef = (FileUploadFile) msg;
            byte[] bytes = ef.getBytes();
            byteRead = ef.getEndPos();
            String md5 = ef.getFile_md5();//文件名
//            String path = NetworkConfig.getProfile() + File.separator + md5;
            String path = NetworkConfig.getProfile() + ef.getFilePath();
            File file = new File(path);
            if(!file.getParentFile().exists()){
                file.getParentFile().mkdirs();
            }
            RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rws");
            if(ef.getBytes().length!=0){
                randomAccessFile.seek(start);
                randomAccessFile.write(bytes);
                start = start + byteRead;
                System.out.println("写入文件长度"+start);
                System.out.println("长度"+ef.getLength());
                ctx.writeAndFlush(start);
                randomAccessFile.getChannel().close();
                randomAccessFile.close();
                return;
            }
            randomAccessFile.getChannel().close();
            randomAccessFile.close();
            ctx.close();
            System.out.println("写入完成");

        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}
